package com.uit.trip.tab_activity.childs;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.FbDialog;
import com.uit.trip.R;
import com.uit.trip.TripApplication;
import com.uit.trip.bridge.Parser;
import com.uit.trip.bridge.Server;
import com.uit.trip.models.CommentItem;
import com.uit.trip.models.Trip;
import com.uit.trip.models.User;
import com.uit.trip.tab_activity.Tab_TripHomeActivity;
import com.uit.trip.utils.FileCommon;
import com.uit.trip.utils.IconContextMenu;
import com.uit.trip.utils.IconContextMenu.IconContextMenuOnClickListener;
import com.uit.trip.utils.ShareTrip;

public class CommentActivity extends ListActivity {

	private CommentAdapter adapter;
	private List<CommentItem> commentList;
	private EditText commentContent;
	private TextView likes;
	private TextView userLikes;
	public static final String FINISH_LOADING_COMMENTS = "finish";
	public static final String FINISH_LOADING_LIKES = "likes";
	public static final String FINISH_ALIKE = "alike";
	public static final int DIALOG_SHARE = 1;

	private User user;
	private Trip trip;
	private Server server;
	private List<String> likeList;
	private CommentReceiver commentReceiver;
	private ListLikeReceiver likeReceiver;

	private IconContextMenu iconContextMenu;
	private ImageButton btLike;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.home_comment);
		adapter = new CommentAdapter();
		server = new Server(this);
		iconContextMenu = new IconContextMenu(CommentActivity.this,
				DIALOG_SHARE);
		iconContextMenu.setOnClickListener(onIconContextMenuClick);
		commentList = new ArrayList<CommentItem>();
		likeList = new ArrayList<String>();
		commentContent = (EditText) this.findViewById(R.id.commentText);
		trip = new Trip();
		LayoutInflater inflater = getLayoutInflater();
		View header = inflater.inflate(R.layout.row_header, getListView(),
				false);
		ImageView imgComment = (ImageView) header.findViewById(R.id.imgComment);
		TextView name = (TextView) header.findViewById(R.id.tvUserName);
		TextView tvDate = (TextView) header.findViewById(R.id.tvTimeComment);
		btLike = (ImageButton) header.findViewById(R.id.btLikeComment);
		likes = (TextView) header.findViewById(R.id.tvLikes);
		userLikes = (TextView) header.findViewById(R.id.tvUserLikes);

		// likes.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// if (likeList.size() > 0) {
		// Log.i("duongnx", msg)
		// showDialog(0);
		// }
		// }
		// });
		Bundle extras = getIntent().getExtras();
		TripApplication app = (TripApplication) getApplication();
		if (extras != null) {
			int index = extras.getInt("position");
			int type = extras.getInt("type");
			if (app.getTripList(type) != null) {
				trip = app.getTripList(type).get(index);
				name.setText(trip.userName);
			}
		}
		user = app.getUser();

		if (trip.bitmap != null) {
			imgComment.setImageBitmap(trip.bitmap);
		}
		tvDate.setText("" + trip.time);
		if (trip.isLike == 1) {
			likes.setText("1");
			userLikes.setText("" + user.userName);
			btLike.setEnabled(false);
			btLike.setImageResource(R.drawable.like_red);
		} else {
			btLike.setEnabled(true);
			btLike.setImageResource(R.drawable.like);
		}

		getListView().addHeaderView(header);
		setListAdapter(adapter);
		getComments();
		getListUserlLikes();

		commentReceiver = new CommentReceiver();
		likeReceiver = new ListLikeReceiver();

	}

	// Get comment data from server
	private void getComments() {
		server.getListComments(trip.imgId);
	}

	private void getListUserlLikes() {
		server.getListUserLikes(trip.imgId);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case 0:
			Dialog dialog = new Dialog(this);
			// dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
			dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
					android.R.drawable.ic_dialog_info);

			dialog.setTitle(likeList.size() + " likes");
			dialog.setContentView(R.layout.dialog_likes);
			TextView tv = (TextView) dialog.findViewById(R.id.tvlike);
			String likeStr = "";
			for (int i = 0; i < likeList.size(); i++) {
				if (i != likeList.size() - 1) {
					likeStr += likeList.get(i) + ", ";
				} else {
					likeStr += likeList.get(i);
				}
			}

			tv.setText(likeStr);
			return dialog;

		case DIALOG_SHARE:
			iconContextMenu.addItem(getResources(), "Facebook",
					R.drawable.icon_face, Tab_TripHomeActivity.SHARE_FACEBOOK);
			iconContextMenu.addItem(getResources(), "Twitter",
					R.drawable.icon_twitle, Tab_TripHomeActivity.SHARE_TWITTER);
			iconContextMenu.addItem(getResources(), "Email",
					R.drawable.icon_mail, Tab_TripHomeActivity.SHARE_EMAIL);
			return iconContextMenu.createMenu("Share picture via:");

		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	/*
	 * Click to send comment
	 */
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btSendComment:
			String comment = commentContent.getText().toString();
			commentContent.setText("");
			if (comment != null && !comment.equals("")) {
				// Insert comment
				DateFormat d = DateFormat.getDateTimeInstance();
				String timeStamp = d.format(new Date());
				CommentItem item = new CommentItem(user.userId, user.userName,
						comment, timeStamp);
				commentList.add(item);
				adapter.notifyDataSetChanged();
				server.postComment(trip.imgId, user.userId, item);
			}
			break;
		case R.id.btLikeComment:
			btLike.setEnabled(false);
			btLike.setImageResource(R.drawable.like_red);
			trip.isLike = 1;
			server.postLike(trip.imgId, user.userId);
			likeList.add("" + user.userName);
			showListLike();
			break;

		case R.id.btShareComment:
			showDialog(DIALOG_SHARE);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(commentReceiver);
		unregisterReceiver(likeReceiver);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		IntentFilter i = new IntentFilter(FINISH_LOADING_COMMENTS);
		registerReceiver(commentReceiver, i);
		IntentFilter j = new IntentFilter(FINISH_LOADING_LIKES);
		registerReceiver(likeReceiver, j);

	}

	private class CommentAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return commentList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return commentList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parentView) {
			// TODO Auto-generated method stub
			View row;
			CommentItem item = commentList.get(position);
			if (convertView == null) {
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.row_comment, parentView, false);
			} else {
				row = convertView;
			}
			TextView cmName = (TextView) row.findViewById(R.id.cmName);
			TextView cmContent = (TextView) row.findViewById(R.id.cmContent);
			TextView cmDate = (TextView) row.findViewById(R.id.cmDate);

			cmName.setText(item.userName);
			cmContent.setText(item.comment);
			cmDate.setText(item.date);
			return row;
		}

	}

	private class CommentReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

			Bundle extras = intent.getExtras();
			if (extras == null) {
				return;
			}
			String response = extras.getString("response");

			commentList = Parser.parseListComments(response);
			adapter.notifyDataSetChanged();
		}
	}

	private class ListLikeReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent i) {
			// TODO Auto-generated method stub
			Bundle extras = i.getExtras();
			if (extras == null) {
				return;
			}
			String response = extras.getString("response");
			likeList = Parser.parseListUserLikes(response);
			showListLike();
		}

	}

	private void showListLike() {
		likes.setText(likeList.size() + " likes");
		if (likeList.size() > 0) {
			String result = "";
			for (int j = 0; j < likeList.size(); j++) {
				if (j == likeList.size() - 1) {
					result += likeList.get(j);
				} else {
					result += likeList.get(j) + ", ";
				}
			}
			userLikes.setText(result);
		} else {
			userLikes.setVisibility(View.GONE);
		}
	}

	public void sharePhotoViaEmail(Bitmap bitmap) {
		// B1: lay duong dan luu anh
		String mPath = FileCommon.getOutputFile();
		// B2: Luu anh
		if (mPath != null && !mPath.equalsIgnoreCase("")) {
			FileCommon.saveImageFile(this, bitmap);
			// Send anh
			sendEmailImageFile(mPath);
		}
	}

	private void sendEmailImageFile(String pPathImage) {

		Uri iData = FileCommon.getOutputMediaFileUri(pPathImage);
		try {
			Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
			emailIntent.setType("message/rfc822");
			emailIntent.putExtra(Intent.EXTRA_STREAM, iData);

			startActivityForResult((Intent.createChooser(emailIntent,
					"Choose an Email client:")),
					Tab_TripHomeActivity.SHARE_EMAIL);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "Your device doesn't support to send email! ",
					Toast.LENGTH_LONG).show();
		}
	}

	IconContextMenuOnClickListener onIconContextMenuClick = new IconContextMenuOnClickListener() {

		@Override
		public void onClick(int menuId) {
			// TODO Auto-generated method stub

			switch (menuId) {
			case Tab_TripHomeActivity.SHARE_FACEBOOK:
				if (ShareTrip.getInstance(getApplicationContext())
						.appInstalledOrNot("com.facebook.katana")) {

					if (trip != null) {
						Toast.makeText(getApplicationContext(),
								"Your photo is uploading...",
								Toast.LENGTH_SHORT).show();
						ShareTrip.getInstance(getApplicationContext())
								.sharePhotoToFacebook(trip.imgId, user);
					} else {
						Toast.makeText(getApplicationContext(),
								"Can not share. Please try again",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(getApplicationContext(),
							"Please install Facebook app first",
							Toast.LENGTH_SHORT).show();
				}

				break;
			case Tab_TripHomeActivity.SHARE_TWITTER:
				ShareTrip.getInstance(getApplicationContext()).shareTwitter(
						trip.imgId);
				break;

			case Tab_TripHomeActivity.SHARE_EMAIL:
				Toast.makeText(getApplicationContext(), "Share Email...",
						Toast.LENGTH_SHORT).show();
				sharePhotoViaEmail(trip.bitmap);
				break;

			default:
				break;
			}

		}
	};

}
